<?php

/**
 * Класс обработки шаблонов
 *
 */
class Template {
  private $var = array();
  private $filename = '';
  /**
   * Адрес директории с шаблонами
   * @var string
   */
  public static $folder='';
  
  
  
  public function __construct($name, $mod=null) {
    is_null( $mod ) && $mod = mod::$current;
    $mod = mod::get_name( $mod );
    if ( $mod !== 'system' &&
         file_exists( $this->filename = 'mod/' . $mod . '/tmpl/' . $name . '.phtml' ) )
      { return; }
    if ( !file_exists( $this->filename = self::$folder . $name . '.phtml' ) ) {
      trigger_error( 'Template "'.$name.'" not found', E_USER_NOTICE );
      $this->filename = '';
    }
  }

  /**
   * Assign a value to be substituted in the template
   * @param $var
   * @param $val
   * @return Template
   */
  public function assign( $var, $val ) {
    $this->var[$var] = $val;
    return $this;
  }
  
  /**
   * assign values from associative array
   * @param $array
   * @return Template
   */
  public function assign_r(array $array ) {
    foreach( $array as $var => $val ) {
      $this->assign( $var, $val );
    }
    return $this;
  }
     
  /**
   * Add a value to be substituted in the template
   * @param $var
   * @param $val
   * @return unknown_type
   */
  public function add( $var, $val ) {
    if ( !array_key_exists( $var, $this->var ) || !is_array( $this->var[$var] ) ) {
      $this->var[$var] = array();
    }
    $this->var[$var][] = $val;
    return $this;
  }
  
  public function process() {
    if ( !file_exists($this->filename) ) { return null; }
    if ( defined('DEBUG') ) {
      $err = error_reporting();
      error_reporting( $err & ~E_NOTICE );
    }
    extract( $this->var );
    ob_start();
    include $this->filename;
    defined('DEBUG') && error_reporting( $err );
    return ob_get_clean();
  }

  
  public function flush() {
    if ( !file_exists($this->filename) ) { return false; }
    if ( defined('DEBUG') ) {
      $err = error_reporting();
      error_reporting( $err & ~E_NOTICE );
    }
    extract( $this->var );
    include $this->filename;
    defined('DEBUG') && error_reporting( $err );
    return true;
  }
  
  public function __toString() {
    return $this->process();
  }
  
}


?>